﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FrasesSimpsonsMvc.Models;

namespace FrasesSimpsonsMvc.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController() : base() { }

        private const int QuantityOfFrasesInHome = 15;
        private const int QuantityOfTopPersonajes = 5;
        private const int QuantityOfAutocomplete = 8;

        public ActionResult Index()
        {
            //ESql
            var query = Context.CreateQuery<Frases>(@"Select VALUE source.entity From (Select entity, SqlServer.NewID() as rand From Frases as entity) as source Order by source.rand");
            var ultimasFrases = query.Take(QuantityOfFrasesInHome).ToList();

            foreach (var f in ultimasFrases)
            {
                f.LoadRelatedEntities();
            }

            var topPersonajes = (from p in Context.Personajes
                                 orderby p.Frases.Count() descending
                                 select p).Take(QuantityOfTopPersonajes);

            ViewData["TopPersonajes"] = topPersonajes.ToList();

            ViewData["Temporadas"] = Context.Temporadas.ToList();

            return View(ultimasFrases.ToList());
        }

        public ActionResult Search(string q)
        {
            var resultadoFrases = PrivateSearch(q);

            foreach (var f in resultadoFrases)
            {
                f.LoadRelatedEntities();
            }

            ViewData["SearchQuery"] = q;

            return View(resultadoFrases.ToList());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AutocompleteSearch(string q)
        {
            var resultadoFrases = PrivateSearch(q);

            return Json(resultadoFrases.Select(f => f.Descripcion).Take(QuantityOfAutocomplete).ToArray());
        }

        private IQueryable<Frases> PrivateSearch(string q)
        {
            var busquedaLower = q.ToLower();

            var resultadoFrases = from f in Context.Frases
                                  where f.Descripcion.ToLower().Contains(busquedaLower) || f.Dialogo.ToLower().Contains(busquedaLower) || f.Keywords.ToLower().Contains(busquedaLower)
                                  orderby f.Fecha descending
                                  select f;

            return resultadoFrases;
        }

        public ActionResult InvalidCaptcha()
        {
            return View();
        }

    }
}
